<?
################################################################################
# _superlibrary_.php                                                           #
################################################################################
# PHP Super Library File v1.0 ?2003 Carlos Barreto Feitoza Filho               #
# Script escrito por Carlos Barreto Feitoza Filho                              #
# Contato: carlos.feitoza.filho@click21.com.br ou ICQ: 29391688 (Authorize)    #
# Dispon?vel em http://www.wildstarcorp.kit.net - Se??o de downloads           #
# NOTA: Aceito sugest?es para melhorias, mas n?o aceitarei cr?ticas de nenhuma #
#       esp?cie! 8^)                                                           #
# ---------------------------------------------------------------------------- #
# NOME DO PROGRAMA: PHP Super Library File                                     #
# VERS?O: 1.0                                                                  #
# ?LTIMA MODIFICA??O: 10/12/2003                                               #
# ============================================================================ #
# INFORMA??ES DE COPYRIGHT:                                                    #
#                                                                              #
# Copyright (c)2003 Carlos Barreto Feitoza Filho. Todos os direitos reservados #
#                                                                              #
# Este programa ? gratuito; voc? pode modifica-lo como  quiser. Por?m, vers?es #
# modificadas n?o  podem ser  vendidas ou distribu?das. Voc? n?o pode  alterar #
# esta informa??o de copyright.                                                #
#                                                                              #
# GARANTIA LIMITADA:                                                           #
#                                                                              #
# ESTE  PROGRAMA  ?  DISTRIBU?DO  NO  INTUITO  DE  SER ?TIL, MAS SEM QUAISQUER #
# GARANTIAS; N?O ME RESPONSABILIZO POR QUAISQUER DANOS  OU  INCONVENIENTES QUE #
# ELE VENHA CAUSAR.                                                            #
################################################################################
################################################################################
# Constantes e Variaveis Globais                                               #
################################################################################
####### Diret?rio dos templates. Pode ser um caminho completo ou relativo ######
define("_TEMPLATESDIR", "_templates_/");
##################### Par?metros default da fun??o DieNice #####################
define("_DIENICETITLE","ERRO");
define("_DIENICETEXT","Erro desconhecido");
define("_DIENICEFORMAT",true);
define("_DIENICEINTERRUPT",false);
########################### Path para o log de erros ###########################
define("_ERRORLOG","Errors.log");
##################### Par?metros default da fun??o Warning #####################
define("_WARNINGTEXT","Nada a declarar");
define("_WARNINGINTERRUPT",false);
define("_WARNINGFORMAT",true);
################### Par?metros default da fun??o SetMyCookie ###################
define("_SETMYCOOKIEENCRIPT",false);
define("_SETMYCOOKIEEXPIRE",7200);
################### Par?metros default da fun??o GetMyCookie ###################
define("_GETMYCOOKIEDECRIPT",false);
define("_GETMYCOOKIEKEY","");
################### Par?metros default da fun??o UploadFile ####################
define("_UPLOADFILEUPLOADDIR","Uploads/");
define("_UPLOADFILEUPLOADTYPE","application/zip");
define("_UPLOADFILEUPLOADSIZE","8192->512000");
####### Par?metros default da fun??o PrepareFileToInsertIntoTableAsBlob ########
define("_GETFILEASBLOBFILETYPE","application/zip");
define("_GETFILEASBLOBFILESIZE","8192->512000");
############################# Array de tipos MIME ##############################
$MIMETypes = array (
	############################################################ application/* ###########################################################
	"ez"      => "application/andrew-inset",       "hqx"     => "application/mac-binhex40",        "cpt"           => "application/mac-compactpro",
	"doc"     => "application/msword",             "bin"     => "application/octet-stream",        "dms"           => "application/octet-stream",
	"lha"     => "application/octet-stream",       "lzh"     => "application/octet-stream",        "exe"           => "application/octet-stream",
	"class"   => "application/octet-stream",       "so"      => "application/octet-stream",        "dll"           => "application/octet-stream",
	"oda"     => "application/oda",                "pdf"     => "application/pdf",                 "ai"            => "application/postscript",
	"eps"     => "application/postscript",         "ps"      => "application/postscript",          "smi"           => "application/smil",
	"smil"    => "application/smil",               "mif"     => "application/vnd.mif",             "xls"           => "application/vnd.ms-excel",
	"ppt"     => "application/vnd.ms-powerpoint",  "wbxml"   => "application/vnd.wap.wbxml",       "wmlc"          => "application/vnd.wap.wmlc",
	"wmlsc"   => "application/vnd.wap.wmlscriptc", "bcpio"   => "application/x-bcpio",             "vcd"           => "application/x-cdlink",
	"pgn"     => "application/x-chess-pgn",        "cpio"    => "application/x-cpio",              "csh"           => "application/x-csh",
	"dcr"     => "application/x-director",         "dir"     => "application/x-director",          "dxr"           => "application/x-director",
	"dvi"     => "application/x-dvi",              "spl"     => "application/x-futuresplash",      "gtar"          => "application/x-gtar",
	"hdf"     => "application/x-hdf",              "js"      => "application/x-javascript",        "skp"           => "application/x-koan",
	"skd"     => "application/x-koan",             "skt"     => "application/x-koan",              "skm"           => "application/x-koan",
	"latex"   => "application/x-latex",            "nc"      => "application/x-netcdf",            "cdf"           => "application/x-netcdf",
	"sh"      => "application/x-sh",               "shar"    => "application/x-shar",              "swf"           => "application/x-shockwave-flash",
	"sit"     => "application/x-stuffit",          "sv4cpio" => "application/x-sv4cpio",           "sv4crc"        => "application/x-sv4crc",
	"tar"     => "application/x-tar",              "tcl"     => "application/x-tcl",               "tex"           => "application/x-tex",
	"texinfo" => "application/x-texinfo",          "texi"    => "application/x-texinfo",           "t"             => "application/x-troff",
	"tr"      => "application/x-troff",            "roff"    => "application/x-troff",             "man"           => "application/x-troff-man",
	"me"      => "application/x-troff-me",         "ms"      => "application/x-troff-ms",          "ustar"         => "application/x-ustar",
	"src"     => "application/x-wais-source",      "xhtml"   => "application/xhtml+xml",           "xht"           => "application/xhtml+xml",
	"tsp"     => "application/dsptype",            "zip"     => "application/zip",                 "pfr"           => "application/font-tdpfr",
	"stk"     => "application/hyperstudio",        "vmd"     => "application/vocaltec-media-desc", "vmf"           => "application/vocaltec-media-file",
	"ico"     => "application/octet-stream",       "ani"     => "application/octet-stream",        "cur"           => "application/octet-stream",
	"web"     => "application/vnd.xara", 	         "xar"     => "application/vnd.xara",            "wiz"           => "application/x-InstallShield",
	"dwg"     => "application/x-autocad", 	       "dxf"     => "application/x-autocad",           "chat"          => "application/x-chat",
	"z"       => "application/x-compress",         "co"      => "application/x-cult3d-object",     "ipx"           => "application/x-ipix",
	"ips"     => "application/x-ipscript",         "jnlp"    => "application/x-java-jnlp-file",    "wmd"           => "application/x-ms-wmd",
	"wmz"     => "application/x-ms-wmz",           "rar"     => "application/x-rar",
	############################################################### audio/* ##############################################################
	"au"      => "audio/basic",                    "snd"     => "audio/basic",                     "imy"           => "audio/melody",
	"mid"     => "audio/midi",                     "midi"    => "audio/midi",                      "kar"           => "audio/midi",
	"mpga"    => "audio/mpeg",                     "mp2"     => "audio/mpeg",                      "mp3"           => "audio/mpeg",
	"aif"     => "audio/x-aiff",                   "aiff"    => "audio/x-aiff",                    "aifc"          => "audio/x-aiff",
	"m3u"     => "audio/x-mpegurl",                "ram"     => "audio/x-pn-realaudio",            "rm"            => "audio/x-pn-realaudio",
	"rpm"     => "audio/x-pn-realaudio-plugin",    "ra"      => "audio/x-realaudio",               "wav"           => "audio/x-wav",
	"m3url"   => "audio/x-mpegurl",                "mod"     => "audio/x-mod",                     "m15"           => "audio/x-mod",
	"s3m"     => "audio/x-mod",                    "stm"     => "audio/x-mod",                     "ult"           => "audio/x-mod",
	"xm"      => "audio/x-mod",                    "wax"     => "audio/x-ms-wax",                  "wma"           => "audio/x-ms-wma",
	"wmv"     => "audio/x-ms-wmv",                 "rmm"     => "audio/x-realaudio",               "rmf"           => "audio/x-rmf",
	############################################################## drawing/* #############################################################
	"dwf"     => "drawing/x-dwf",
	############################################################## chemical/* ############################################################
	"pdb"     => "chemical/x-pdb",                 "xyz"     => "chemical/x-xyz",
	############################################################### image/* ##############################################################
	"gif"     => "image/gif",                      "ief"     => "image/ief",                       "jpeg"          => "image/jpeg",
	"jpg"     => "image/jpeg",                     "jpe"     => "image/jpeg",                      "png"           => "image/png",
	"tiff"    => "image/tiff",                     "tif"     => "image/tiff",                      "djvu"          => "image/vnd.djvu",
	"djv"     => "image/vnd.djvu",                 "wbmp"    => "image/vnd.wap.wbmp",              "ras"           => "image/x-cmu-raster",
	"pnm"     => "image/x-portable-anymap",        "pbm"     => "image/x-portable-bitmap",         "pgm"           => "image/x-portable-graymap",
	"ppm"     => "image/x-portable-pixmap",        "rgb"     => "image/x-rgb",                     "xbm"           => "image/x-xbitmap",
	"xpm"     => "image/x-xpixmap",                "xwd"     => "image/x-xwindowdump",             "igs"           => "model/iges",
	"bmp"     => "image/bmp", 	                   "svh"     => "image/SVH",                       "nokia-op-logo" => "image/vnd.nok-oplogo-color",
	############################################################### model/* ##############################################################
	"iges"    => "model/iges",                     "msh"     => "model/mesh",                      "mesh"          => "model/mesh",
	"silo"    => "model/mesh",
	############################################################# i-world/* ##############################################################
	"ivr"     => "i-world/i-vrml",
	############################################################# x-world/* ##############################################################
	"wrl"     => "x-world/x-vrml",                 "vrml"    => "x-world/x-vrml",
	############################################################### text/* ###############################################################
	"css"     => "text/css",                       "html"    => "text/html",                       "htm"           => "text/html",
	"asc"     => "text/plain",                     "txt"     => "text/plain",                      "rtx"           => "text/richtext",
	"rtf"     => "text/rtf",                       "sgml"    => "text/sgml",                       "sgm"           => "text/sgml",
	"tsv"     => "text/tab-separated-values",      "wml"     => "text/vnd.wap.wml",                "wmls"          => "text/vnd.wap.wmlscript",
	"etx"     => "text/x-setext",                  "xsl"     => "text/xml",                        "xml"           => "text/xml",
	"hts"     => "text/html",                      "dhtml"   => "text/html",                       "hdml"          => "text/x-hdml",
	"shtml"   => "text/x-server-parsed-html",      "mel"     => "text/x-vmel",
	############################################################### video/* ##############################################################
	"mpeg"    => "video/mpeg",                     "mpg"     => "video/mpeg",                      "mpe"           => "video/mpeg",
	"qt"      => "video/quicktime",                "mov"     => "video/quicktime",                 "mxu"           => "video/vnd.mpegurl",
	"avi"     => "video/x-msvideo",                "movie"   => "video/x-sgi-movie",               "vivo"          => "video/vnd",
	"viv"     => "video/vnd",                      "asf"     => "video/x-ms-asf",                  "asx"           => "video/x-ms-asf",
	"wm"      => "video/x-ms-wm",                  "wvx"     => "video/x-ms-wvx",                  "wmx"           => "video/x-mx-wmx",
	"movie"   => "video/x-sgi-movie",
	########################################################### x-conference/* ###########################################################
	"ice"     => "x-conference/x-cooltalk"
);

################################################################################
# Exibidor de erros - Exibe na tela uma mensagem formatada de  erro segundo um #
# =================   arquivo externo de nome _error_template.tpl              #
################################################################################
function DieNice($Titulo = _DIENICETITLE, $Texto = _DIENICETEXT, $Formatar = _DIENICEFORMAT, $Interromper = _DIENICEINTERRUPT) {
	$ErrorDateTime = DateHour();
	$StringData = "{$ErrorDateTime['DiaSemana']}, {$ErrorDateTime['DiaMes']} de {$ErrorDateTime['MesAno']} de {$ErrorDateTime['Ano']} ?s {$ErrorDateTime['Horas']}:{$ErrorDateTime['Minutos']}:{$ErrorDateTime['Segundos']}";
	$Linha = str_repeat("=", 91 - strlen($StringData));
	$TextoLocal = wordwrap($Texto,93);
	$ArquivoErro = __FILE__;
	$LinhaErro = __LINE__;
	$ErrorLog = <<<EOLOG
$StringData $Linha
Script onde ocorreu o problema: $ArquivoErro
linha do erro: $LinhaErro
M?todo de acesso: {$_SERVER["REQUEST_METHOD"]}
Query String: {$_SERVER["QUERY_STRING"]}
Referer: {$_SERVER["HTTP_REFERER"]}
Browser utilizado: {$_SERVER["HTTP_USER_AGENT"]}
IP Chamador: {$_SERVER["REMOTE_ADDR"]} ({$_SERVER["REMOTE_HOST"]})
Mensagem de erro:

$TextoLocal
============================================================================================\n
EOLOG;
	if (file_exists(_ERRORLOG)) {
		if (is_writable(_ERRORLOG)) {
			$LogHandle = fopen(_ERRORLOG, 'a');
			fwrite($LogHandle, $ErrorLog);
			fclose($LogHandle);
		}
	} else {
		$LogHandle = fopen(_ERRORLOG, 'a');
		chmod (_ERRORLOG, 0777);
		fwrite($LogHandle, $ErrorLog);
		fclose($LogHandle);
	}

	$Chaves  = array("?TITULO?", "?TEXTO?", "?NOME_DO_SCRIPT?", "?REFERER?");
	$Valores = array($Titulo, $Texto, $_SERVER["PHP_SELF"], $_SERVER["HTTP_REFERER"]);

	$TemplateHandle = fopen(_TEMPLATESDIR."_error_template.tpl", "rb") or exit("Template de erros n?o encontrado em "._TEMPLATESDIR);
	$ConteudoTemplate = fread($TemplateHandle, filesize(_TEMPLATESDIR."_error_template.tpl"));

	fclose($TemplateHandle);

	if ($Formatar) {
		echo str_replace($Chaves, $Valores, $ConteudoTemplate);
	} else {
		echo "$Titulo<br>\n$Texto<br>\nScript com problemas: <b>{$_SERVER['PHP_SELF']}</b><br>\nClique <a href=\"{$_SERVER['HTTP_REFERER']}\">aqui</a> para retornar a p?gina que gerou este erro";
	}

	if ($Interromper) {
		exit(1);
	}

	return true;
}

################################################################################
# Abridor e "tradutor" de templates - Abre  um  arquivo  externo  substituindo #
# =================================   neste cada uma das chaves pelos  valores #
# correspondentes.   Retorna    uma    String  contendo  exatemente  o   mesmo #
# conte?do  do  arquivo original,  so que   com as   chaves substitu?das pelos #
# valores.                                                                     #
################################################################################
function OpenTranslatingTemplate($NomeTemplate, $Chaves, $Valores) {
	$TemplateHandle = fopen($NomeTemplate, "rb") or DieNice("&iexcl;Template n?o encontrado!","O template informado ($NomeTemplate) n?o existe");
	$ConteudoTemplate = fread ($TemplateHandle, filesize ($NomeTemplate));

	fclose($TemplateHandle);

	return str_replace($Chaves, $Valores, $ConteudoTemplate);
}

################################################################################
# Alerta ao usu?rio - Exibe uma informa??o qualquer que n?o seja um erro       #
################################################################################
function Warning ($Texto = _WARNINGTEXT, $Formatar = _WARNINGFORMAT, $Interromper = _WARNINGINTERRUPT){
	$Chaves  = array("?TEXTO?", "?NOME_DO_SCRIPT?", "?REFERER?");
	$Valores = array($Texto, $_SERVER["PHP_SELF"], $_SERVER["HTTP_REFERER"]);

	if ($Formatar) {
		echo OpenTranslatingTemplate(_TEMPLATESDIR."_warning_template.tpl",$Chaves,$Valores);
	} else {
		echo "$Texto<br>\n<b>{$_SERVER['PHP_SELF']}</b><br>\nClique <a href=\"{$_SERVER['HTTP_REFERER']}\">aqui</a> para retornar a p?gina que gerou este aviso";
	}

	if ($Interromper) {
		exit(1);
	}

	return true;
}

################################################################################
# Exibidor de linha de copyright - Exibe  um texto predefinido de acordo com o #
# ==============================   formato definido em _copyright_template.tpl #
################################################################################
function Copyright() {
	echo OpenTranslatingTemplate(_TEMPLATESDIR."_copyright_template.tpl","?TEXTO?","Copyright 2004 by Carlos Feitoza Filho");
}

################################################################################
# Data e hor?rio - Este  procedimento  define  um  array  associativo  com  as #
# ==============   seguintes chaves: Segundos, Minutos, Horas, DiaMes,  MesAno #
# Ano, DiaSemana, DiaAno, HorarioVerao. Se nenum par?metro  for passado,  essa #
# fun??o  retorna  a  data  atual. Se um  argumento inteiro for  passado  como #
# par?metro esse valor ser? usado para se retornar a dara correspondente.      #
################################################################################
function DateHour($Valor = 0) {
	$DiasSemana = array("Domingo","Segunda-feira","Ter?a-feira","Quarta-feira","Quinta-feira","Sexta-feira","S?bado");
	$Meses = array("Janeiro","Fevereiro","Mar?o","Abril","Maio","Junho","Julho","Agosto","Stembro","Outubro","Novembro","Dezembro");

	$DataHoraLocal = $Valor > 0?localtime($Valor,true):localtime(time(),true);

	$DataHoraResultado["Horas"]        = $DataHoraLocal["tm_hour"] < 10?"0{$DataHoraLocal['tm_hour']}":$DataHoraLocal["tm_hour"];
	$DataHoraResultado["Minutos"]      = $DataHoraLocal["tm_min"] < 10?"0{$DataHoraLocal['tm_min']}":$DataHoraLocal["tm_min"];
	$DataHoraResultado["Segundos"]     = $DataHoraLocal["tm_sec"] < 10?"0{$DataHoraLocal['tm_sec']}":$DataHoraLocal["tm_sec"];
	$DataHoraResultado["Ano"]          = $DataHoraLocal["tm_year"] + 1900;
	$DataHoraResultado["DiaSemana"]    = $DiasSemana[$DataHoraLocal["tm_wday"]];
	$DataHoraResultado["DiaMes"]       = $DataHoraLocal["tm_mday"];
	$DataHoraResultado["MesAno"]       = $Meses[$DataHoraLocal["tm_mon"]];
	$DataHoraResultado["Mes"]          = $DataHoraLocal["tm_mon"] + 1;
	$DataHoraResultado["DiaAno"]       = $DataHoraLocal["tm_yday"];
	$DataHoraResultado["HorarioVerao"] = $DataHoraLocal["tm_isdst"];

	return $DataHoraResultado;
}

################################################################################
# Salvar Cookie - Esta fun??o salva um cookie simples ou um cookie m?ltiplo de #
# =============   de acordo  com os  par?metros  passados. Tamb?m  ?  poss?vel #
# salvar  os   cookies   encriptados    (base64).  O  Par?metro $NomeCookie  ? #
# o nome do cookie  a ser salvo,  j?  o  par?metro  $ValorCookie ? o  que deve #
# ser salvo no cookie e  pode ser uma string  simples  ou um array. Se for  um #
# array  a  fun??o detecta  um   cookie  multiplo,  isto   ?, um  cookie   que #
# armazena v?rios  pares chave/valor,   nesse caso,   cada elemento   do array #
# dever? ter   a  forma  Chave<=>Valor.  Tamb?m    ?   poss?vel    passar  uma #
# string   como   um  cookie  m?ltiplo,    bastando     para   isso    cri?-la #
# da      seguinte        maneira:   Chave1<=>Valor1?Chave2<=>Valor2...      O #
# caractere    "?"     ?    o    separador.  $Expiracao    ?    o   tempo   de #
# expira??o do  cookie  e ?  medido  em segundos contados a partir do  momento #
# em que o cookie estiver sendo salvo                                          #
################################################################################
function SetMyCookie($NomeCookie, $ValorCookie, $Criptograr = _SETMYCOOKIEENCRIPT, $Expiracao = _SETMYCOOKIEEXPIRE) {
	if (count($ValorCookie) > 1) {// cookie ? m?ltiplo
		if ($Criptograr){
			setcookie($NomeCookie,base64_encode(implode("?",$ValorCookie)),time() + $Expiracao);
		} else {
			setcookie($NomeCookie,implode("?",$ValorCookie),time() + $Expiracao);
		}
	}	else if (count($ValorCookie) == 1) {// cookie ? simples
		if ($Criptograr){
			setcookie($NomeCookie,base64_encode($ValorCookie),time() + $Expiracao);
		} else {
			setcookie($NomeCookie,$ValorCookie,time() + $Expiracao);
		}
	} else {
		DieNice("Chamada inv?lida", "A fun??o \"SetMyCookie\" foi chamada incorretamente");
	}
}

################################################################################
# Obter Cookie - Esta  fun??o  recupera o valor de um cookie. $NomeCookie ?  o #
# ============   nome do cookie  do qual o valor se  quer obter  o valor. Se o #
# cookie for m?ltiplo e nenhuma chave foi passada no par?metro $Chave ent?o  a #
# linha contendo os pares Chave/Valor ser? retornada. Caso o  par?metro $Chave #
# contenha o nome  de uma chave,  ser? retornado  apenas o valor dessa  chave! #
# Quando $Descriptografar ? true, o valor do cookie  ? descriptografado  antes #
# de qualquer coisa ser feita                                                  #
################################################################################
function GetMyCookie($NomeCookie, $Descriptografar = _GETMYCOOKIEDECRIPT, $Chave = _GETMYCOOKIEKEY) {
	if (isset($_COOKIE[$NomeCookie])) {
		$ValorCookie = $Descriptografar?base64_decode($_COOKIE[$NomeCookie]):$_COOKIE[$NomeCookie];

		/*Verificando se ? um cookie m?ltiplo ou simples */
		if (strstr($ValorCookie,"?")) { // M?ltiplo
			if ($Chave == "") {
				return $ValorCookie;
			} else {
				$ValorCookieArray = explode("?",$ValorCookie);
				for ($i = 0; i < count($ValorCookieArray); $i++) {
					list($TempChave, $TempValor) = explode("<=>",$ValorCookieArray[$i]); // chave<=>valor
					if ($TempChave == $Chave) {
						return $TempValor;
					}
				}
				DieNice("Chave inexistente", "No Cookie $NomeCookie n?o existe a chave informada ($Chave)", true, true);
			}
		} else { //Simples
			return $ValorCookie;
		}
	} else {
		return "";
	}
}

################################################################################
# Excluir Cookie - Esta  fun??o  exclui  o cookie referenciado por $NomeCookie #
# ==============   al?m  de destruir  a  sua  referencia no  array  global  de #
# cookies                                                                      #
################################################################################
function DeleteMyCookie($NomeCookie) {
	if (isset($_COOKIE[$NomeCookie]))	{
		unset($_COOKIE[$NomeCookie]);
	}
	setcookie($NomeCookie,"",time() - 7200);
}

################################################################################
# Conector de banco MySQL - Estabelece uma conec??o com um banco MySQL segundo #
# =======================   par?metros passados                                #
################################################################################
function ConnectToMySQLDatabase($NomeHost, $NomeBanco, $Usuario, $Senha) {
	$LinkToDataBase = mysql_connect($NomeHost, $Usuario, $Senha) or DieNice("Erro de Conec??o MySQL","N?o foi poss?vel conectar-se ao banco <b>$NomeBanco</b> em <b>$NomeHost</b>. Abaixo segue informa??es adicionais sobre o erro:<br>".mysql_errno().": ".mysql_error(),true,true);
	return mysql_select_db($NomeBanco, $LinkToDataBase) or DieNice("Erro de Conec??o MySQL","N?o foi poss?vel selecionar o banco <b>$NomeBanco</b> em <b>$NomeHost</b>. Abaixo segue informa??es adicionais sobre o erro:<br>".mysql_errno().": ".mysql_error(),true,true);
}

################################################################################
# Preparador de Dados Bin?rios - Esta fun??o tem apenas um prop?sito. Preparar #
# ============================   os dados de um  arquivo passado no  par?metro #
# $FileResource para que ele possa ser salvo  em um campo BLOB de um banco  de #
# dados. $FileResource uma referencia ao arquivo que se quer salvar e pode ser #
# por exemplo algo como $_FILES["campo"], onde campo ? o nome do campo de tipo #
# "file"  no  form de  upload.  $FileNumber ?  o  n?mero do  arquivo  no vetor #
# $_FILES, no caso de terem sido transferidos mais de um arquivo. $FileType  e #
# $FileSize representam respectivamente os tipos MIME aceitos pelo processo  e #
# a faixa  de tamanhos  de arquivo  permitidos. Esta fun??o tem 2 retornos. Se #
# tudo  ocorrer  bem,  um  vetor  associativo  ser?  retornado  com  as chaves #
# "nome", "tipo"",  tamanho", "nome_temporario"  e "dados",  do contr?rio  uma #
# string vazia  ("") ser?  retornada, por  isso esta  fun??o deve ser colocada #
# dentro de uma condi??o da seguinte maneira:                                  #
#                                                                              #
# if ($var = GetFileAsBLOB(...)) {                                             #
# 	$newvar = $var                                                             #
# }                                                                            #
################################################################################
function GetFileAsBLOB($FileResource, $FileNumber = 0, $FileType = _GETFILEASBLOBFILETYPE, $FileSize = _GETFILEASBLOBFILESIZE) {
	$TiposAceitos = strstr($FileType,";")?explode(";",$FileType):$FileType;
	$TamanhosAceitos = strstr($FileSize,"->")?explode("->",$FileSize):$FileSize;

	/* Verificando se h? mais de um arquivo na lista de arquivos */
	$ArquivosEnviados = count($FileResource["name"]);
	if ($ArquivosEnviados > 1) { // Mais de um arquivo
		/* Verificando se houve algum erro interno */
		if ($FileResource["error"][$FileNumber] == 0) {
			if (($FileResource["size"][$FileNumber] != 0) && ($FileResource["tmp_name"][$FileNumber] != "none")){

				/* Verificando se o arquivo ? de um tipo v?lido */
				if (is_array($TiposAceitos)) {
					if (!in_array($FileResource["type"][$FileNumber],$TiposAceitos)) {
						return "";
					}
				} else {
					if ($FileResource["type"][$FileNumber] != $TiposAceitos) {
						return "";
					}
				}

				/* Verificando se o arquivo ? de um tamanho v?lido */
				if (is_array($TamanhosAceitos)) {
					if (($FileResource["size"][$FileNumber] < $TamanhosAceitos[0]) || ($FileResource["size"][$FileNumber] > $TamanhosAceitos[1])) {
						return "";
					}
				} else {
					if (($FileResource["size"][$FileNumber] < 1024) || ($FileResource["size"][$FileNumber] > $TamanhosAceitos)) {
						return "";
					}
				}

				$InfoArquivo["nome"] = $FileResource["name"][$FileNumber];
				$InfoArquivo["tipo"] = $FileResource["type"][$FileNumber];
				$InfoArquivo["tamanho"] = $FileResource["size"][$FileNumber];
				$InfoArquivo["nome_temporario"] = $FileResource["tmp_name"][$FileNumber];
				$InfoArquivo["dados"] = addslashes(fread(fopen($FileResource["tmp_name"][$FileNumber], "rb"), filesize($FileResource["tmp_name"][$FileNumber])));
				return $InfoArquivo;

			}
			return "";
		} else if (($FileResource["error"][$FileNumber] == 1) || ($FileResource["error"][$FileNumber] == 2) ||
							 ($FileResource["error"][$FileNumber] == 3) || ($FileResource["error"][$FileNumber] == 4)) {

			return "";
		}
	} else { // Apenas um arquivo
		/* Verificando se houve algum erro interno */
		if ($FileResource["error"] == 0) {
			if (($FileResource["size"] != 0) && ($FileResource["tmp_name"] != "none")){

				/* Verificando se o arquivo ? de um tipo v?lido */
				if (is_array($TiposAceitos)) {
					if (!in_array($FileResource["type"],$TiposAceitos)) {
						return "";
					}
				} else {
					if ($FileResource["type"] != $TiposAceitos) {
						return "";
					}
				}

				/* Verificando se o arquivo ? de um tamanho v?lido */
				if (is_array($TamanhosAceitos)) {

					if (($FileResource["size"] < $TamanhosAceitos[0]) || ($FileResource["size"] > $TamanhosAceitos[1])) {
						return "";
					}
				} else {
					if (($FileResource["size"] < 1024) || ($FileResource["size"] > $TamanhosAceitos)) {
						return "";
					}

				}

				$InfoArquivo["nome"] = $FileResource["name"];
				$InfoArquivo["tipo"] = $FileResource["type"];
				$InfoArquivo["tamanho"] = $FileResource["size"];
				$InfoArquivo["nome_temporario"] = $FileResource["tmp_name"];
				$InfoArquivo["dados"] = addslashes(fread(fopen($FileResource["tmp_name"], "rb"), filesize($FileResource["tmp_name"])));
				return $InfoArquivo;
			}
			return "";

		} else if (($FileResource["error"] == 1) || ($FileResource["error"] == 2) ||
							 ($FileResource["error"] == 3) || ($FileResource["error"] == 4)) {

			return "";
		}
	}
}

################################################################################
# Validador de arquivos - Valida o  upload de um certo arquivo,  salvando-o no #
# =====================   servidor  em um diret?rio definido  por  $UploadDir. #
# Esta   fun??o  deve   ser  chamada  no   script  de  upload   de  arquivos e #
# retornar? true  se  todoas  as  condi??es passadas  nos   seus    par?metros #
# tiverem  sido  satisfeitas.    $UploadType  define   o  MIME   aceito   para #
# upload.  Separe  v?rios MIMEs   com  ";".   $UploadSize define   a faixa  de #
# tamanhos de arquivo  para upload. Separe    o  limite  inferior    do limite #
# superior   com "->". Se apenas um valor for dado, indica que n?o h?  tamanho #
# m?nimo  e  subtende-se   que   s?  o   limite   m?ximo    foi  estabelecido. #
# $UploadField ?  o nome  do campo  no formul?rio de upload que tem o  nome do #
# arquivo  a  ser enviado.    Esse   campo, em   termos  de  formul?rio,  ?  o #
# TYPE="upload".  Em  caso de  erro, essa fun??o retorna um vetor  associativo #
# contendo a mensagem  de erro  como valor  e o nome  de arquivo  onde o  erro #
# aconteceu como sendo a chave  ("NomeDoArquivo" => "Erro ocorrido"). Uma  boa #
# maneira de usar essa fun??o ? a seguinte:                                    #
#     																																				 #
# $retorno = UploadFile("campo_no_Form");                                      #
# if  (is_array($retorno)) {                                                   #
#		foreach ($retorno as $chave => $valor) {                                   #
#			... Fa?a algo com $chave e $valor, mostrando-os talvez ...               #
#   }                                                                          #
# }                                                                            #
################################################################################
function UploadFile($UploadField, $UploadDir = _UPLOADFILEUPLOADDIR, $UploadType = _UPLOADFILEUPLOADTYPE, $UploadSize = _UPLOADFILEUPLOADSIZE) {
	$TiposAceitos = strstr($UploadType,";")?explode(";",$UploadType):$UploadType;
	$TamanhosAceitos = strstr($UploadSize,"->")?explode("->",$UploadSize):$UploadSize;

	/* Verificando se fora feito upload e mais de um arquivo */
	$ArquivosEnviados = count($_FILES[$UploadField]["name"]);
	if ($ArquivosEnviados > 1) { //Mais de um arquivo foi enviado

		/* Realizando opera??es de valida??o em cada arquivo enviado */
		for ($i = 0;$i < $ArquivosEnviados;$i++) {
			/* Verificando se houve algum erro interno */
			if ($_FILES[$UploadField]["error"][$i] == 0) {
				/* Verificando se o arquivo ? de um tipo v?lido */
				if (is_array($TiposAceitos)) {
					if (!in_array($_FILES[$UploadField]["type"][$i],$TiposAceitos)) {
						$VetorErros[$_FILES[$UploadField]["name"][$i]] = "O tipo MIME <b>".$_FILES[$UploadField]["type"][$i]."</b> do arquivo <b>".$_FILES[$UploadField]["name"][$i]."</b> n?o foi reconhecido como um tipo aceito.";
						continue;
					}
				} else {
					if ($_FILES[$UploadField]["type"][$i] == $TiposAceitos) {
						$VetorErros[$_FILES[$UploadField]["name"][$i]] = "O tipo MIME <b>".$_FILES[$UploadField]["type"][$i]."</b> do arquivo <b>".$_FILES[$UploadField]["name"][$i]."</b> n?o foi reconhecido como um tipo aceito.";
						continue;
					}
				}

				/* Verificando se o arquivo ? de um tamanho v?lido */
				if (is_array($TamanhosAceitos)) {
					if (($_FILES[$UploadField]["size"][$i] < $TamanhosAceitos[0]) || ($_FILES[$UploadField]["size"][$i] > $TamanhosAceitos[1])) {
						$VetorErros[$_FILES[$UploadField]["name"][$i]] = "O tamanho do arquivo n?o ? v?lido, ele est? fora dos limites estabelecidos.";
						continue;
					}
				} else {
					if (($_FILES[$UploadField]["size"][$i] < 1024) || ($_FILES[$UploadField]["size"][$i] > $TamanhosAceitos)) {
						$VetorErros[$_FILES[$UploadField]["name"][$i]] = "O tamanho do arquivo n?o ? v?lido, ele est? fora dos limites estabelecidos.";
						continue;
					}
				}

				/* movendo o arquivo atual do loop para o seu local de destino */
				if (!move_uploaded_file($_FILES[$UploadField]['tmp_name'][$i], $UploadDir.$_FILES[$UploadField]['name'][$i])) {
					$VetorErros[$_FILES[$UploadField]["name"][$i]] = "N?o foi poss?vel salvar o arquivo ".$UploadDir.$_FILES[$UploadField]['name'][$i]." no servidor";
				}
			} else if ($_FILES[$UploadField]["error"][$i] == 1) {
				$VetorErros["Sistema$i"] = "O tamanho do arquivo que se est? tentando enviar ? maior que o limite estabelacido pelo servidor. Escolha um arquivo menor.";
			} else if ($_FILES[$UploadField]["error"][$i] == 2) {
				$VetorErros["Sistema$i"] = "O tamanho do arquivo que se est? tentando enviar ? maior que o limite estabelacido em MAX_FILE_SIZE no formul?rio HTML. Escolha um arquivo menor.";
			} else if ($_FILES[$UploadField]["error"][$i] == 3) {
				$VetorErros["Sistema$i"] = "O arquivo foi enviado parcialmente e pode estar corrompido.";
			} else if ($_FILES[$UploadField]["error"][$i] == 4) {
				$VetorErros["Sistema$i"] = "Nenhum arquivo foi especificado para upload.";
			}
		} // Loop FOR que circula por cada um dos arquivos enviados
	} else { //Apenas um arquivo foi enviado
		/* Verificando se houve algum erro interno */
		if ($_FILES[$UploadField]["error"] == 0) {
			/* Verificando se o arquivo ? de um tipo v?lido */
			if (is_array($TiposAceitos)) {
				if (!in_array($_FILES[$UploadField]["type"],$TiposAceitos)) {
					$VetorErros[$_FILES[$UploadField]["name"]] = "O tipo MIME <b>".$_FILES[$UploadField]["type"]."</b>do arquivo <b>".$_FILES[$UploadField]["name"]."</b> n?o foi reconhecido como um tipo aceito.";
				}
			} else {
				if ($_FILES[$UploadField]["type"] == $TiposAceitos) {
					$VetorErros[$_FILES[$UploadField]["name"]] = "O tipo MIME <b>".$_FILES[$UploadField]["type"]."</b>do arquivo <b>".$_FILES[$UploadField]["name"]."</b> n?o foi reconhecido como um tipo aceito.";
				}
			}

			/* Verificando se o arquivo ? de um tamanho v?lido */
			if (is_array($TamanhosAceitos)) {
				if (($_FILES[$UploadField]["size"] < $TamanhosAceitos[0]) || ($_FILES[$UploadField]["size"] > $TamanhosAceitos[1])) {
					$VetorErros[$_FILES[$UploadField]["name"]] = "O tamanho do arquivo n?o ? v?lido, ele est? fora dos limites estabelecidos.";
				}
			} else {
				if (($_FILES[$UploadField]["size"] < 1024) || ($_FILES[$UploadField]["size"] > $TamanhosAceitos)) {
					$VetorErros[$_FILES[$UploadField]["name"]] = "O tamanho do arquivo n?o ? v?lido, ele est? fora dos limites estabelecidos.";
				}
			}

			/* movendo o arquivo para o seu local de destino */
			if (!move_uploaded_file($_FILES[$UploadField]['tmp_name'], $UploadDir.$_FILES[$UploadField]['name'])) {
				$VetorErros[$_FILES[$UploadField]["name"]] = "N?o foi poss?vel salvar o arquivo ".$UploadDir.$_FILES[$UploadField]['name']." no servidor";
			}
		} else if ($_FILES[$UploadField]["error"] == 1) {
			$VetorErros["Sistema"] = "O tamanho do arquivo que se est? tentando enviar ? maior que o limite estabelacido pelo servidor. Escolha um arquivo menor.";
		} else if ($_FILES[$UploadField]["error"] == 2) {
			$VetorErros["Sistema"] = "O tamanho do arquivo que se est? tentando enviar ? maior que o limite estabelacido em MAX_FILE_SIZE no formul?rio HTML. Escolha um arquivo menor.";
		} else if ($_FILES[$UploadField]["error"] == 3) {
			$VetorErros["Sistema"] = "O arquivo foi enviado parcialmente e pode estar corrompido.";
		} else if ($_FILES[$UploadField]["error"] == 4) {
			$VetorErros["Sistema"] = "Nenhum arquivo foi especificado para upload.";
		}
	}

	/* Definindo o retorno da fun??o de acordo com poss?veis erros encontrados ou n?o */
	if (count($VetorErros) == 0) { //Sem erros!
		return true;
	} else {
		return $VetorErros;
	}
}

################################################################################
# Validador de senhas - Esta  fun??o  toma  como  par?metros  uma senha  que o #
# ===================   usu?rio digitou e a senha correta criptografada  com a #
# fun??o cript() que n?o  possui processo  inverso, o que  garante uma  grande #
# seguran?a. A fun??o compara o que foi digitado como senha com uma string que #
# ? a senha esperada, sem fazer qualquer descriptografia.                      #
################################################################################
function ValidatePassword($UserInput, $EncryptedPassword) {
	return (crypt($UserInput, $EncryptedPassword) == $EncryptedPassword)?true:false;
}

################################################################################
# Detector de tipos MIME - Esta  fun??o  recebe  como par?metro  o nome de  um #
# ======================   arquivo e retorna o tipo MIME deste arquivo baseado #
# em sua extens?o.                                                             #
################################################################################
function DetectMIMEType($FileName) {
	if (trim($FileName) != "") {
		global $MIMETypes;
		$Path_Parts = pathinfo($FileName);
		return $MIMETypes[$Path_Parts["extension"]];
	}
}

################################################################################
# Justificador Num?rico - Esta  fun??o  completa  com  uma certa quantidade de #
# ======================  caracteres  um  dado  valor  num?rido.  O  par?metro #
# $format tem duas fun??es, ele  indica com qual  caractere ser? completado  o #
# valor e  tamb?m  o  tamanho  do  texto  no final.  $valor  ? o numero a  ser #
# justificado (Cr?ditos a Keitaro San)                                         #
################################################################################
function JustifyNumber($format, $valor) {
	if (strlen($valor) < strlen($format)) {
      $dif = strlen($format) - strlen($valor);
      for ($cont = $dif; $cont > 0; $cont--) {
        $valor = $format[$cont -1] . $valor;
      }
      return $valor;
    }
  }

################################################################################
################################################################################
################################################################################
# Se esta biblioteca for chamada diretamente da linha de comando  um erro ser? #
# apresentado                                                                  #
################################################################################
if (!defined("USO_CORRETO")) {
	DieNice();
}
?>